package cc.yihy.storage.upyun.bean;

import cc.yihy.storage.StorageClient;
import cc.yihy.storage.entity.UpResult;
import main.java.com.UpYun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Yihy
 * @version V1.0
 * @Package cc.yihy.storage
 * @Description:
 * @date 2017/6/27 15:50
 */
public class SimpleUpYunClient implements StorageClient {

    private final static Logger log = LoggerFactory.getLogger(SimpleUpYunClient.class);
    private UpYun upyun;
    private String domain;

    public SimpleUpYunClient(UpYun upyun, String domain) {

        this.upyun = upyun;
        this.domain = domain;
    }


    public UpResult upload(InputStream inputStream, String fileName) {
        UpResult result = new UpResult();
        boolean bFlag = false;

        try {
            byte[] buffer = null;

            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = inputStream.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            inputStream.close();
            bos.close();
            buffer = bos.toByteArray();


            if (buffer != null) bFlag = upyun.writeFile(fileName, buffer);

        } catch (Exception e) {
            e.printStackTrace();
        }

        result.setSuccess(bFlag);

        result.setFileName(fileName);

        return result;

    }

    //普通上传
    public UpResult upload(String filePath, String fileName) throws IOException {
        UpResult result = new UpResult();
        boolean bFlag = false;

        try {
            String md5Value = UpYun.md5(filePath);
            upyun.setContentMD5(md5Value);     // 计算文件 MD5，如果文件太大或计算不便，可以不计算
            bFlag = upyun.writeFile(fileName, filePath);

            result.setUnique(md5Value);
            result.setFileName(fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        result.setSuccess(bFlag);
        return result;
    }

    public String getDomain() {
        return domain;
    }

    public String getImageUrl(String fileName) {
        return new StringBuilder(domain).append("/").append(fileName).toString();
    }

    @Override
    public boolean delete(String fileKey) {
        return upyun.deleteFile(fileKey);
    }

}
